package com.springboot.auth.authorization.oauth2;

import com.springboot.auth.authorization.entity.User;
import com.springboot.auth.authorization.provider.OrganizationProvider;
import com.springboot.auth.authorization.service.IUserService;
import com.springboot.auth.authorization.util.RedisUtils;
import com.springboot.cloud.common.core.utils.EncryptUtils;
import com.springboot.cloud.common.core.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * Created by ZengJian on 2021/2/3 0003 上午 9:22
 * 手机验证码登陆, 用户相关获取
 */
@Slf4j
@Service("mobileUserDetailsService")
public class MobileUserDetailsService extends CustomUserDetailsService {

    @Autowired
    private IUserService userService;

    @Lazy
    @Autowired
    private PasswordEncoder passwordEncoder;

    @Resource
    private RedisUtils redisUtils;

//    @Autowired
//    private SmsCodeProvider smsCodeProvider;

    @Autowired
    private OrganizationProvider organizationProvider;

    @Override
    public UserDetails loadUserByUsername(String uniqueId) throws UsernameNotFoundException {

        User user = userService.getByUniqueId(uniqueId);
        if (user == null) {
            throw new UsernameNotFoundException("不存在该用户");
        }
        log.info("load user by mobile:{}", user.toString());

        // 如果为mobile模式，从短信服务中获取验证码（动态密码）
//        String credentials = smsCodeProvider.getSmsCode(uniqueId, "LOGIN");


        String credentialss = EncryptUtils.getEncrypt(organizationProvider.getSms(uniqueId));

        //首先比对验证码是否失效
        String redisauthcode = organizationProvider.getSms(uniqueId); //传入tonkenId返回redis中的value
        System.out.println("redisauthcode:" + redisauthcode);
        if (StringUtils.isEmpty(redisauthcode)) {
            //如果未取到则过期验证码已失效
            throw new UsernameNotFoundException("验证码已过期");
        }
//        else  if(!"".equals(redisauthcode)){
//            //验证码错误
//            throw new UsernameNotFoundException("验证码错误");
//        }
        String credentials = passwordEncoder.encode(credentialss);
//        EncryptUtils.getEncrypt(smsCodeProvider.getSms(uniqueId));

        return new org.springframework.security.core.userdetails.User(
                user.getUsername(),
                credentials,
                user.getEnabled(),
                user.getAccountNonExpired(),
                user.getCredentialsNonExpired(),
                user.getAccountNonLocked(),
                super.obtainGrantedAuthorities(user));
    }
}
